package com.zkzx.company.api.controller.company;

import com.zkzx.common.company.command.ModifyCompanyPasswordCommand;
import com.zkzx.common.exception.BaseException;
import com.zkzx.common.exception.ExceptionEnum;
import com.zkzx.common.sms.constants.SmsTypeEnum;
import com.zkzx.company.api.controller.BaseController;
import com.zkzx.company.api.mapper.entity.Member;
import com.zkzx.company.api.service.authorization.MemberMapperService;
import com.zkzx.util.redis.CacheKeyUtil;
import com.zkzx.util.redis.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * @author young Email:yanghui@zkraising.com
 * @description
 * @company 北京中科智兴物联科技有限公司 @版权所有
 * @since 2021年05月18日 16时27分
 */
@RestController
@Validated
@Api(tags="企业管理 - 基础信息")
@RequestMapping(value = "/company")
public class CompanyController extends BaseController {

    @Autowired
    private MemberMapperService memberMapperService;
    @Autowired
    private RedisUtil redisUtil;


    @PutMapping("/password")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "修改企业登录密码", notes = "修改企业登录密码")
    public void updatePwd( @RequestBody @Valid ModifyCompanyPasswordCommand command) {

        SmsTypeEnum smsTypeEnum = SmsTypeEnum.UPDATE_LOGIN_PASSWORD;

        // 根据type+手机号 生成缓存KEY 判断有没有发生验证码 防止刷接口
        String key = CacheKeyUtil.getCaptcha(smsTypeEnum.name(), command.getPhone());
        boolean keyBoolean = redisUtil.hasKey(key);
        if (!keyBoolean){
            throw new BaseException(ExceptionEnum.VERIFICATION_CODE_OVERDUE_ERROR.getCode(), ExceptionEnum.VERIFICATION_CODE_OVERDUE_ERROR.getMsg());
        }
        // 手机号获取企业信息 通过手机号直接修改
        Member member = memberMapperService.getByMobile(command.getPhone());
        if (Objects.isNull(member)){
            throw new BaseException(ExceptionEnum.UPDATE_PASSWORD_CODE_ERROR.getCode(),ExceptionEnum.UPDATE_PASSWORD_CODE_ERROR.getMsg());
        }

        memberMapperService.updatePassword(member.getId(),command.getPassword());


    }

}
